<template>
    <div class="top">
        <div class="left">
            <span>订单提交成功，请尽快付款！订单号:</span>
            <b style="color:red;">{{ detail?.order_id }}</b>
        </div>
        <div class="total_fee">
            应付金额
            <b style="color:red;font-size:20px">
                {{ detail?.total_fee }}
            </b>
            元
        </div>
    </div>
    <div class="payment">
        <div class="title">
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-wechat_pay">
                </use>
            </svg>
            <b>
                微信支付
            </b>
            <span>请使用微信扫码支付</span>
        </div>
        <div class="main">
            <div class="left">
                <div class="qrcode" v-loading="qrLoading">
                    <!-- 展示二维码的地方 -->
                    <img :src="qrSrc" width="300" height="300" alt="">
                    <div class="pw-box-ft">
                        <div class="svg">
                            <svg class="icon">
                                <use xlink:href="#icon-weixin1"></use>
                            </svg>
                        </div>
                        <div class="qr-right">
                            <p>请使用微信扫一扫</p>
                            <p>扫描二维码支付</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="right">

            </div>
        </div>
        <el-descriptions title="订单信息">
            <el-descriptions-item label="创建时间">{{ detail?.create_time
            }}</el-descriptions-item>
            <el-descriptions-item label="用户名">
                {{ detail?.user_nickname }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
                {{ detail?.user_phone }}
            </el-descriptions-item>
            <el-descriptions-item label="产品名称">
                {{ detail?.orderDetail[0].productName }}
            </el-descriptions-item>
            <el-descriptions-item label="产品描述">
                {{ detail?.orderDetail[0].description }}
            </el-descriptions-item>
            <el-descriptions-item label="收件地址">
                {{ detail?.address }}
            </el-descriptions-item>
        </el-descriptions>
    </div>
</template>
<script setup>
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import * as api from "@/api/pay"
import { onUnmounted, ref } from "vue"
//引入生成二维码的库
import qr from "qrcode"
let route = useRoute()
let router = useRouter()
//声明一个定时器
let timeout = null;
// 1.发起请求,根据query传递过来的order_id,获取订单详情
let { order_id } = route.query
//声明响应式变量存储订单的详情
let detail = ref()
//一个响应式变量储存二维码地址
let qrSrc = ref("")
//一个二维码展示的加载动画
let qrLoading = ref(false)
let getOrder = async () => {
    qrLoading.value = true;
    try {
        let res = await api.getOrderApi(order_id)
        //订单状态 order_status:订单状态:0未提交 1提交成功 2已经取消 3无效订单 4.交易关闭 5退货
        //也就意味着订单状态为1的时候才能够发起支付
        console.log(res)
        //获取订单状态
        let { order_status } = res.data.data;
        detail.value = res.data.data;
        console.log(detail.value)
        //如果没有订单id
        if (!order_id) {
            ElMessage({
                type: 'error',
                message: '没有获取到订单id,2秒后将跳转充值页'
            })
        }

        if (order_status === 1) {
            // 先从本地查询一下,这个订单有没有发起过支付
            let code_url = localStorage.getItem(order_id)
            if (code_url) {//这个订单已经发起过支付,可能用户没有支付
                console.log(code_url)
                //使用qrcode将支付地址,变成二维码
                qr.toDataURL(code_url, (err, url) => {
                    // console.log(url)
                    if (err) {
                        ElMessage.error(err.toString())
                        return
                    }
                    qrSrc.value = url;
                    //关闭加载动画
                    qrLoading.value = false;
                })
            } else {
                //这个状态才可以支付,发起支付请求
                try {
                    let res = await api.paymentApi(order_id)
                    // console.log(res)
                    //因为同一个订单不能频繁发起支付,所以可以使用订单的id作为key,支付的返回的支付地址作为值,放到本地存储中      
                    localStorage.setItem(order_id, res.data.code_url)
                    qr.toDataURL(res.data.code_url, (err, url) => {
                        // console.log(url)
                        if (err) {
                            ElMessage.error(err.toString())
                            return
                        }
                        qrSrc.value = url;
                        //关闭加载动画
                        qrLoading.value = false;
                    })
                } catch (e) {
                    console.log(e)
                }
            }
        } else {
            switch (order_status) {
                case 0:
                    ElMessage({
                        type: 'error',
                        message: '订单未提交,2秒后返回充值页面'
                    })
                    break;
                case 2:
                    ElMessage({
                        type: 'error',
                        message: '订单已取消,2秒后返回充值页面'
                    })
                    break
                case 3:
                    ElMessage({
                        type: 'error',
                        message: '无效订单,2秒后返回充值页面'
                    })
                    break;
                case 4:
                    ElMessage({
                        type: 'error',
                        message: '交易关闭,2秒后返回充值页面'
                    })
            }
            timeout = setTimeout(() => {
                router.push('/vipManager/charge')
            }, 2000)
        }
    } catch (e) {
        console.log(e)
    }
}
getOrder()


//页面卸载的时候,清除定时器 
//使用ajax轮询的方式,来查询支付的状态
//因为http的通信特性,服务端不能主动推送内容给客户端
//轮询:设定一个定时器,间隔性的发送请求,询问服务器,数据是否变化
let poling = () => {
    let interval = setInterval(async () => {
        try {
            let res = await api.queryPayStatusApi(order_id);
            //支付成功,跳转页面到支付成功的页面,清掉本地的缓存的支付地址
            router.push('/pay/paySuccess')
            localStorage.removeItem(order_id)
        } catch (e) {
            if (e.toString() === '交易关闭' || e.toString() === '数据不存在') {
                ElMessage.error(e.toString())
                setTimeout(() => {
                    router.push("/vipManager/charge")
                }, 2000)
            }
        }

    }, 2000);
    return interval
}

let interval = poling();

onUnmounted(() => {
    if (timeout) {
        clearTimeout(timeout)
    }
    clearInterval(interval)
})


//支付流程围绕2步

//1.下单(预支付) 一般携带商品的id和商品的数量

//2.发起支付 调用支付接口 传递订单id


</script>
<style scoped lang="scss">
.payment {
    background-color: #fff;
    padding: 5px 30px;
    box-shadow: 0 6px 32px rgb(0 0 0 / 13%);
}

.main {
    display: flex;
    justify-content: center;
}

.top {
    padding: 5px 5px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;

    .total_fee {
        margin-top: 10px;
    }
}

.title {
    margin: 10px 20px;

    b {
        font-size: 30px;
        display: inline-block;
        margin-right: 135px;
    }

    :deep(.icon) {
        vertical-align: text-bottom;
        width: 2em;
        height: 2em;
        margin-right: 10px;
    }
}

.pw-box-ft {
    height: 44px;
    padding: 8px 0 8px;
    background-image: linear-gradient(135deg, #4c67ff, #5635df);
    display: flex;

    justify-content: space-evenly;

    .qr-right {
        p {
            margin: 0;
            font-size: 14px;
            line-height: 22px;
            color: #fff;
            font-weight: 700;
        }
    }

    .icon {

        width: 3em;
        height: 3em;
    }
}




.right {
    width: 379px;
    height: 421px;
    padding-left: 50px;
    margin-top: -20px;
    background: url(../../../../assets/phone.png) 50px 0 no-repeat;
}
</style>